package com.hostmanagement.servlet;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionValidateFilter implements Filter {


	private static final String TIMEOUT = "timeout";
	private String encoding = null;

	/**
	 * Method init.
	 * 
	 * @param config
	 * @throws javax.servlet.ServletException
	 */
	public void init(FilterConfig config) throws ServletException {

		encoding = config.getInitParameter("encoding");

	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		req.setCharacterEncoding(encoding);

		// user session check
		HttpSession session = request.getSession();

		StringBuffer reqURL = request.getRequestURL();

		System.out.println("reqURL is " + reqURL);
		if (reqURL.indexOf("loginServlet") > 0
				|| reqURL.indexOf("verifyCodeServlet") > 0
				|| reqURL.indexOf("index.jsp") > 1) {
			chain.doFilter(request, response);
		} else if (reqURL.indexOf("Servlet") > 0 || reqURL.indexOf(".jsp") > 1) {
			if (session.getAttribute("userBean") == null) {
				response.sendRedirect("login.jsp?errorCode=" + TIMEOUT);
			}
			chain.doFilter(request, response);
		}
		chain.doFilter(request, response);
	}

	public void destroy() {
		// TODO Auto-generated method stub

	}

}
